package com.egrid.point.bury.service;

import com.egrid.point.bury.dao.BuryPointDao;
import com.egrid.point.bury.dao.PersonDao;
import com.egrid.point.bury.entity.BuryPoint;
import com.egrid.point.bury.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * BuryPointService.java
 * Created at 2019-12-26
 * Created by Royal Warmer
 * Copyright (C) 2018 SAIC VOLKSWAGEN, All rights reserved.
 */
@Service
public class BuryPointService {

    @Autowired
    private BuryPointDao buryPointDao;

    @Autowired
    private PersonDao personDao;

    @Transactional
    public String save(List<BuryPoint> params) {
        List<BuryPoint> list = this.buryPointDao.saveAll(params);
        if (list.size() == params.size()) {
            return "保存成功";
        }
        return "保存失败";
    }


    public List<BuryPoint> findAll() {
        return this.buryPointDao.findAll();
    }

    public Page<BuryPoint> findByPages(int page, int size) {
        Page<BuryPoint> all = this.buryPointDao.findAll(PageRequest.of(page, size));
        return all;
    }

    public void autoinsert() {
        for (int i = 0; i < 10000000; i++) {
            Random random = new Random();

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
            String  date = null;
            LocalDate parse = null;
            while(true) {
                int year = (int) (Math.random() * (2021 - 1900 + 1) + 1900);
                date = year + "";
                int month = random.nextInt(12) + 1;
                if (month < 10) {
                    date += "0" +month;
                } else {
                    date += month;
                }
                int day = random.nextInt(31) + 1;
                if (day < 10) {
                    date += "0" +day;
                } else {
                    date += day;
                }
                try {
                    parse = LocalDate.parse(date, dtf);
                    break;
                } catch (Exception e) {

                }
            }
            this.personDao.save(new Person(date, Date.from(parse.atStartOfDay(ZoneId.systemDefault()).toInstant())));
        }

    }

}
